import { ElNotification } from "element-plus";
import * as XLSX from "xlsx";

/**
 * @description 接收数据生成 blob，创建链接，下载 xlsx 文件
 * @param {Array} data 表格数据 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Array} columns 需要导出的列定义 (必传)
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 */
export const useDownload = async (
  data: any[],
  tempName: string,
  columns: { prop: string; label: string; displayField: string }[],
  isNotify: boolean = true
) => {
  if (!data || data.length === 0) {
    ElNotification({
      title: "提示",
      message: "暂无可导出的数据",
      type: "warning",
      duration: 3000
    });
    return;
  }

  if (isNotify) {
    ElNotification({
      title: "温馨提示",
      message: "正在准备下载文件...",
      type: "info",
      duration: 1000
    });
  }

  try {
    // 构造导出数据：处理数组/对象字段
    const exportData = data.map(row => {
      const exportRow: Record<string, any> = {};
      columns.forEach(col => {
        const value = row[col.prop];

        // 处理数组类型
        if (Array.isArray(value)) {
          exportRow[col.label] = value
            .map(item => {
              // 如果是对象，尝试提取name或title属性，否则JSON.stringify
              if (typeof item === "object" && item !== null) {
                return item[col.displayField] || JSON.stringify(item);
              }
              return item;
            })
            .join(", ");
        }
        // 处理对象类型
        else if (typeof value === "object" && value !== null) {
          exportRow[col.label] = value[col.displayField] || JSON.stringify(value);
        }
        // 基本类型直接使用
        else {
          exportRow[col.label] = value;
        }
      });
      return exportRow;
    });

    // 创建 Sheet 和 Workbook
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    // 设置列宽：自适应每列最大内容长度
    worksheet["!cols"] = columns.map(col => {
      const maxLength = exportData.reduce((max, row) => {
        const cell = row[col.label];
        const cellLength = cell ? String(cell).length : 0;
        return Math.max(max, cellLength);
      }, col.label.length);
      return { wch: Math.min(Math.max(maxLength + 2, 10), 50) }; // 限制最小10，最大50
    });

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

    // 输出为 blob 并触发下载
    const wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
    const blob = new Blob([wbout], { type: "application/octet-stream" });

    const blobUrl = window.URL.createObjectURL(blob);
    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.href = blobUrl;
    exportFile.download = `${tempName}.xlsx`;
    document.body.appendChild(exportFile);
    exportFile.click();
    document.body.removeChild(exportFile);
    await window.URL.revokeObjectURL(blobUrl);

    ElNotification({
      title: "温馨提示",
      message: "下载成功",
      type: "success",
      duration: 3000
    });
  } catch (error) {
    console.error(error);
    ElNotification({
      title: "错误",
      message: "文件下载失败",
      type: "error",
      duration: 3000
    });
  }
};
